#include "mainbox.h"
#include "ui_mainbox.h"

MainBox::MainBox(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MainBox)
{
    ui->setupUi(this);
    this->UI_Init();
    //qDebug() << "MainBox 线程" << QThread::currentThreadId();
}

MainBox::~MainBox()
{
    //退出线程并销毁对象
    ltools_thread->exit();
    ltools_thread->deleteLater();
    ptools_thread->exit();
    ptools_thread->deleteLater();
    delete ui;
}

/*
 * @param:debug浏览器内容
*/
void MainBox::debug(QString s)
{
    QFont ft;
    ft.setPointSize(10);
    ft.setBold(false);
    ui->m_PlainTextEdit->clear();
    ui->m_PlainTextEdit->appendPlainText(s);
    ui->m_PlainTextEdit->setFont(ft);
    ui->m_PlainTextEdit->moveCursor(QTextCursor::End);
}

/*
 * @param:消息内容，消息类型
*/
void MainBox::Logbrowser(QString text, int c)
{
    this->PrintLog(text, c);
    this->SystemInfoBrowser(text, c);
}

void MainBox::SystemInfoBrowser(QString text, int c)
{
    QString log_t = QDateTime::currentDateTime().toString("yyyy/MM/dd HH:mm:ss ");
    log_t.append(text);
    QFont ft;
    ft.setPointSize(10);
    ft.setBold(false);
    ui->m_SystemInfoBrowser->setFont(ft);

    if(c == 0)
    {
        ui->m_SystemInfoBrowser->append("<font color=\"#000000\">" + log_t + "</font>");
    }
    else if (c == 1)
    {
        ui->m_SystemInfoBrowser->append("<font color=\"#ff0000\">" + log_t + "</font>");
    }
    else if (c == 2)
    {
        ui->m_SystemInfoBrowser->append("<font color=\"#00ff00\">" + log_t + "</font>");
    }
    else if (c == 3)
    {
        ui->m_SystemInfoBrowser->append("<font color=\"#0000ff\">" + log_t + "</font>");
    }

    ui->m_SystemInfoBrowser->moveCursor(QTextCursor::End);     //接收到数据滚动到浏览器最后一行

    //日志记录
    m_loghelper->SaveLog(log_t);
}

void MainBox::LineTimeOut()
{
    m_timer->stop();
    this->Logbrowser("连接设备超时", 1);
    flag = false;
    emit DisLine();
}

void MainBox::LineStatus(bool b)
{
    flag = b;
    this->LineDevDisplay(b);
    if(!b)
    {
        QMessageBox::warning(this, "Error", "连接打印机失败");
    }
    m_timer->stop();
}

void MainBox::UpDataConfigJson()
{
    QString arg = ui->m_ProductBox->text();
    QStringList temp = C->ProductList();
    bool contains = temp.contains(arg);

    if(!contains)
    {
        temp.append(arg);
        C->setProductList(temp);
    }

    arg = ui->m_WorkingBox->text();
    temp = C->WorkingList();
    contains = temp.contains(arg);

    if(!contains)
    {
        temp.append(arg);
        C->setWorkingList(temp);
    }

    temp.clear();
}

void MainBox::ClearTextEdit(int num)
{
    if(num == 1)
    {
        QMessageBox::information(this, "Info", "多行数据打印完成");
    }
    ui->m_texteditbox->clear();
}


void MainBox::on_m_PrintData_clicked()
{
    QString text = ui->m_ProductBox->text();
    text = text.replace(',', '-');  //去除,号使用-代替

    if(text.isEmpty())
    {
        this->Logbrowser("产品名异常", 1);
        return;
    }

    ptools->setProduct(text);
    C->setProduct(text);
    text = ui->m_WorkingBox->text();
    text = text.replace(',', '-');  //去除,号使用-代替

    if(text.isEmpty())
    {
        this->Logbrowser("工站名异常", 1);
        return;
    }

    ptools->setWorking(text);
    C->setWorking(text);
    bool bRet;
    int min = ui->m_NumStartBox->text().toInt(&bRet, 10);

    if(!bRet)
    {
        this->Logbrowser("最小编号异常", 1);
        return;
    }

    ptools->setMinnumber(min);
    C->setMinnumber(QString::number(min));
    int max = ui->m_NumStopBox->text().toInt(&bRet, 10);

    if(!bRet)
    {
        this->Logbrowser("最大编号异常", 1);
        return;
    }

    ptools->setMaxnumber(max);
    C->setMaxnumber(QString::number(max));

    if(flag)
    {
        if(ui->m_CheckPrint->isChecked())
        {
            emit SendWorking(true);
        }
        else
        {
            emit SendWorking(false);
        }

        this->UpDataConfigJson();
        C->SaveConfig();
    }
    else
    {
        this->Logbrowser("未连接设备", 1);
    }
}

/*
 * @parame:消息内容,消息类型
 * @birth:根据消息类型输出不同颜色字体到log浏览器
*/
void MainBox::PrintLog(QString s, int color)
{
    QString log_t = QDateTime::currentDateTime().toString("yyyy/MM/dd HH:mm:ss ");
    log_t.append(s);
    QFont ft;
    ft.setPointSize(10);
    ft.setBold(false);
    ui->m_Logbrowser->setFont(ft);

    if(color == 0)
    {
        ui->m_Logbrowser->append("<font color=\"#000000\">" + log_t + "</font>");
    }
    else if (color == 1)
    {
        ui->m_Logbrowser->append("<font color=\"#ff0000\">" + log_t + "</font>");
    }
    else if (color == 2)
    {
        ui->m_Logbrowser->append("<font color=\"#00ff00\">" + log_t + "</font>");
    }
    else if (color == 3)
    {
        ui->m_Logbrowser->append("<font color=\"#0000ff\">" + log_t + "</font>");
    }

    ui->m_Logbrowser->moveCursor(QTextCursor::End);     //接收到数据滚动到浏览器最后一行
}

/*
 * @birth：初始相关内容与UI界面
*/
void MainBox::UI_Init()
{
    //初始化相关工具
    this->Object_Init();
    //初始化UI设置
    ui->m_lineEdit_IP->setInputMask("000.000.000.000;");
    ui->m_lineEdit_IP->setText(C->ip());
    ui->m_lineEdit_Port->setText(C->port());

    ui->m_ProductBox->setText(C->product());
    ui->m_WorkingBox->setText(C->working());
    ui->m_NumStartBox->setText(C->Minnumber());
    ui->m_NumStopBox->setText(C->Maxnumber());


    ui->m_ProductBox_2->setText(C->product());
    ui->m_WorkingBox_2->setText(C->working());
    ui->m_NumberBox->setText(C->ProNumber());

    if(C->ShowPage() == "0")
    {
        ui->m_TabWidget->setCurrentIndex(ui->m_TabWidget->indexOf(ui->m_TabOne));
    }
    else if(C->ShowPage() == "1")
    {
        ui->m_TabWidget->removeTab(ui->m_TabWidget->indexOf(ui->m_tabmanufacture));
    }
    else if (C->ShowPage() == "2")
    {
        ui->m_TabOne->setEnabled(false);
        ui->m_TabTest->setEnabled(false);
    }
    else
    {
        ui->m_TabWidget->removeTab(ui->m_TabWidget->indexOf(ui->m_TabOne));
        ui->m_TabWidget->removeTab(ui->m_TabWidget->indexOf(ui->m_TabTest));
    }
    //ui->m_CheckPrint->setCheckState(Qt::Unchecked);
    //this->setFixedSize(668, 369);
}

/*
 * @birth：初始化相关对象与连接
*/
void MainBox::Object_Init()
{
    L = new QLua;
    C = new QConfigTools;
    m_timer = new QTimer;
    m_timer->setInterval(3000);
    m_loghelper = new QLogHelper;
    m_LineStatus = new QLabel("Test", ui->m_statusBar);
    ui->m_statusBar->setSizeGripEnabled(false);
    this->LineDevDisplay(false);

    //创建连接工具类和工具类线程
    ltools = new QLineTools;
    ltools_thread = new QThread;
    ltools->moveToThread(ltools_thread);
    //创建数据处理类和数据处理线程
    ptools = new QPrintTools;
    ptools_thread = new QThread;
    ptools->moveToThread(ptools_thread);
    connect(m_timer, &QTimer::timeout, this, &MainBox::LineTimeOut);              //连接服务器超时处理器
    connect(ltools, &QLineTools::Result, this, &MainBox::Logbrowser);             //连接工具类的结果绑定到主线程的日志浏览器
    connect(this, &MainBox::SendLine, ltools, &QLineTools::ConnectDev);           //主线程触发连接信号
    connect(this, &MainBox::DisLine, ltools, &QLineTools::DisconnectDev);         //主线程触发关闭连接信号
    connect(this, &MainBox::SendCmd, ltools, &QLineTools::SendData);              //主线程触发数据发送信号
    connect(ptools, &QPrintTools::SendLog, this, &MainBox::Logbrowser);           //打印工具类log信号发送
    connect(ptools, &QPrintTools::SendCommand, ltools, &QLineTools::SendData);    //打印工具类发送数据信号
    connect(ltools, &QLineTools::IsLine, ptools, &QPrintTools::SetLineStatus);    //连接工具类发送的连接状态信号
    connect(ltools, &QLineTools::IsLine, this, &MainBox::LineStatus);             //连接成功，暂停计时器
    connect(this, &MainBox::SendWorking, ptools, &QPrintTools::toMessage);        //主线程安排打印工具干活的信号

    //生产打印
    connect(this, &MainBox::SendMessages, ptools, &QPrintTools::toMessages);
    connect(ptools, &QPrintTools::SendOver, this, &MainBox::ClearTextEdit);
    //规避异常输入
    connect(ui->m_NumStopBox, &QLineEdit::textChanged, [ = ]()
    {
        bool bRet;
        int num = ui->m_NumStartBox->text().toInt(&bRet, 10);

        if(bRet)
        {
            ui->m_NumStopBox->text().toInt(&bRet, 10);

            if(!bRet)
            {
                ui->m_NumStopBox->setText(QString::number(num + 1));
            }
        }
        else
        {
            this->Logbrowser("请先设置最小值", 1);
            ui->m_NumStartBox->setFocus();
        }
    });

    //ui->m_TabWidget->removeTab(ui->m_TabWidget->indexOf(ui->m_TabTest));
    m_ProductCompleter = new QCompleter(C->ProductList(), this);
    m_ProductCompleter->setCaseSensitivity(Qt::CaseInsensitive);
    ui->m_ProductBox->setCompleter(m_ProductCompleter);
    ui->m_ProductBox_2->setCompleter(m_ProductCompleter);


    m_WorkingCompleter = new QCompleter(C->WorkingList(), this);
    m_WorkingCompleter->setCaseSensitivity(Qt::CaseInsensitive);
    ui->m_WorkingBox->setCompleter(m_WorkingCompleter);
    ui->m_WorkingBox_2->setCompleter(m_WorkingCompleter);
    //连接工具线程启动
    ltools_thread->start();
    //打印工具线程启动
    ptools_thread->start();
}

void MainBox::LineTool()
{
    if(this->IP_Port_Verify())
    {
        emit SendLine();
        m_timer->start();
    }
}

bool MainBox::IP_Port_Verify()
{
    QString ip = ui->m_lineEdit_IP->text();
    QRegExp regExpIp("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)");

    if (!regExpIp.exactMatch(ip))
    {
        QMessageBox::information(this, "提示", "ip格式错误");
        return false;
    }
    else
    {
        ltools->setIp(ip);
        C->setIp(ip);
    }

    QString port = ui->m_lineEdit_Port->text();
    QRegExp regExpPort("([0-9]|[1-9]\\d{1,3}|[1-5]\\d{4}|6[0-4]\\d{4}|65[0-4]\\d{2}|655[0-2]\\d|6553[0-5])");

    if (!regExpPort.exactMatch(port))
    {
        QMessageBox::information(this, "提示", "端口格式错误");
        return false;
    }
    else
    {
        ltools->setProt(port.toInt());
        C->setPort(port);
    }

    return true;
}

void MainBox::LineDevDisplay(bool b)
{
    if(b)
    {
        QIcon icon(":/Res/Image/MaterialSymbolsLinkRounded.png");
        m_LineStatus->setPixmap(icon.pixmap(QSize(24, 24)));
        ui->m_statusBar->showMessage("设备连接成功");
    }
    else
    {
        QIcon icon(":/Res/Image/MaterialSymbolsLinkOffRounded.png");
        m_LineStatus->setPixmap(icon.pixmap(QSize(24, 24)));
        ui->m_statusBar->showMessage("设备连接失败");
    }

    ui->m_statusBar->addPermanentWidget(m_LineStatus);
}

void MainBox::on_m_ReadScriptCommand_clicked()
{
    QString sRet = L->GetCommand("PP", "WW", "NN");
    sRet = sRet.simplified();
    sRet = sRet.replace(" ", "\r");
    this->debug(sRet);
}

void MainBox::on_m_LinePrint_clicked()
{
    this->LineTool();
}

void MainBox::on_m_CloseLine_clicked()
{
    if(flag)
    {
        emit DisLine();
    }
    else
    {
        this->Logbrowser("设备未连接", 1);
    }
}

void MainBox::on_m_SendCommand_clicked()
{
    QString _tmp = ui->m_PlainTextEdit->toPlainText();

    if(flag)
    {
        emit SendCmd(_tmp);
    }
    else
    {
        QMessageBox::warning(this, "Error", "未连接设备");
    }
}

void MainBox::on_m_SetPrintIP_clicked()
{
    if(flag)
    {
        emit DisLine();
    }

    this->LineTool();
}

void MainBox::on_m_ResetScript_clicked()
{
    QString log = "";
    QString txt = ui->m_PlainTextEdit->toPlainText();
    QStringList list = txt.split('\n');
    log = L->GetCmd(list);
    log = log.simplified();
    log = log.replace(" ", "\r");
    this->debug(log);
}

void MainBox::on_m_ScriptPrint_clicked()
{
    QString log = ui->m_Logbrowser->toPlainText();
    m_loghelper->SaveLog(log);
    ui->m_Logbrowser->clear();
}

void MainBox::on_m_LinePrint_2_clicked()
{
    if(flag)
    {
        this->LineDevDisplay(flag);
        return;
        //emit DisLine();
    }

    this->LineTool();
}

void MainBox::on_m_PrintData_2_clicked()
{
    QString text = ui->m_ProductBox_2->text();
    text = text.replace(',', '-');  //去除,号使用-代替

    if(text.isEmpty())
    {
        this->Logbrowser("产品名异常", 1);
        return;
    }

    ptools->setProduct(text);
    C->setProduct(text);
    text = ui->m_WorkingBox_2->text();
    text = text.replace(',', '-');  //去除,号使用-代替

    if(text.isEmpty())
    {
        this->Logbrowser("工站名异常", 1);
        return;
    }

    ptools->setWorking(text);
    C->setWorking(text);
    bool bRet;
    int min = ui->m_NumberBox->text().toInt(&bRet, 10);

    if(!bRet)
    {
        this->Logbrowser("治具编号异常", 1);
        return;
    }

    ptools->setProNumber(QString::number(min));
    C->setProNumber(QString::number(min));

    QString txt = ui->m_texteditbox->toPlainText();
    QStringList pt = txt.split('\n');
    QStringList tmpLisst = {};
    foreach(const QString &s, pt)
    {
        if(!s.isEmpty())
        {
            tmpLisst.append(s);
        }
    }
    if(tmpLisst.isEmpty())
    {
        this->Logbrowser("数据无效", 1);
        return;
    }
    emit SendMessages(tmpLisst);

    this->UpDataConfigJson();
    C->SaveConfig();
}
